package com.tgh.gles2;

import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;

public abstract class ControlPanelRendererActivity extends RendererActivity implements OnTouchListener {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View controlPanel = getLayoutInflater().inflate(R.layout.layout_control, mLayout, false);
        controlPanel.findViewById(R.id.left).setOnTouchListener(this);
        controlPanel.findViewById(R.id.right).setOnTouchListener(this);
        controlPanel.findViewById(R.id.up).setOnTouchListener(this);
        controlPanel.findViewById(R.id.down).setOnTouchListener(this);
        FrameLayout.LayoutParams params=new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
        params.gravity=Gravity.BOTTOM;
        mLayout.addView(controlPanel, params);
    }
    @Override
    protected void onResume() {
        super.onResume();
        mSurfaceView.setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);
    }
    private int id;
    private boolean flag=true;
    protected int speedFactor=100;
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction()==MotionEvent.ACTION_DOWN) {
            id=v.getId();
            flag=true;
            new Thread(longClick).start();
            return true;
        }else if (event.getAction()==MotionEvent.ACTION_UP) {
            flag=false;
            return true;
        }
        return false;
    }
    
    protected  Runnable rendererTask=new Runnable() {
        @Override
        public void run() {
            switch (id) {
                case R.id.left:
                    onPressLeft();
                    break;
                case R.id.right:
                    onPressRight();
                    break;
                case R.id.up:
                    onPressUp();
                    break;
                case R.id.down:
                    onPressDown();
                    break;
                default:
                    break;
            }
        }
    };
    
    protected Runnable longClick =new Runnable() {
        @Override
        public void run() {
            while (flag) {
               mSurfaceView.queueEvent(rendererTask);
               try {
                Thread.sleep(speedFactor);
                } catch (InterruptedException e) {}
            }
        }
    };
    
    abstract protected void onPressLeft();
    abstract protected void onPressRight();
    abstract protected void onPressUp();
    abstract protected void onPressDown();
}
